//
//  CircleScrollView.m
//  TAOVideo
//
//  Created by Lin Eidan on 13-8-12.
//  Copyright (c) 2013年 taomee. All rights reserved.
//

#import "CircleScrollView.h"
#import "config.h"
#import "UIView+EidanSize.h"
#import "Common.h"

#define AutoPlayTime        8
#define PageControlDisToBottom      0   //翻页控件离底部的距离

#define ImageContainerViewTag       300   //这个要和xib中的保持一致,两张图片view的背景view，xib的结构应该保持这样，不要更改。。
#define LabelContainerViewTag       999   //这个要和xib中的保持一致,label的背景view。。


@implementation CircleScrollView

//正常的初始化
- (id)initWithFrame:(CGRect)frame andPageXibName:(NSString *)pageXibName
{
    self = [super initWithFrame:frame];
    if (self) {
        self.pageXibName = pageXibName;
        self.isCanAuto = YES;
        
       [self setUp];
    }
    return self;
}

//公共的setUp
-(void)setUp{

    
    self.myScrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
    self.myScrollView.delegate=self;
    self.myScrollView.pagingEnabled=YES;
    self.myScrollView.showsHorizontalScrollIndicator=NO;
    self.myScrollView.showsVerticalScrollIndicator=NO;
    [self addSubview:self.myScrollView];
    [self.myScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    self.myPageControl=[[UIPageControl alloc] initWithFrame:CGRectMake(0, 0, 0, 20)];
    self.myPageControl.pageIndicatorTintColor = RGB(204, 204, 204);
    self.myPageControl.currentPageIndicatorTintColor = RGB(48, 122, 149);
    [self addSubview:self.myPageControl];
    
}


-(void)drawContainerWithTotalNums:(int)totalNums andOrientation:(CircleOrientation)orientaion{
    
    [self.myScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    self.curPageIndex=0;
    self.isScrollRunFlag=NO;
    
    self.myPageControl.numberOfPages=totalNums;
    self.myPageControl.width=[self.myPageControl sizeForNumberOfPages:totalNums].width;
    self.myPageControl.right=self.width-10;
    self.myPageControl.bottom=self.height-PageControlDisToBottom;
    self.myPageControl.currentPage=self.curPageIndex;
    
    self.totalPage=totalNums;
    self.floatOrientation=orientaion;
    
    [self drawPageViews];
}


//－－－－－－－－－－－－－－－－－－－－－－－－－－－公共 start －－－－－－－－－－－－－－－－－－－－－－

-(void)removeTheTimer{
    [self.autoPlayTimer invalidate];
}

-(void)drawPageViews{
    float unitX=0.0;
    float unitY=0.0;
    int totalPageTemp=3;
    
    if (self.floatOrientation == CircleOrientationLandscape) {
        unitX=self.myScrollView.width;
        self.myScrollView.contentSize=CGSizeMake(self.myScrollView.width*totalPageTemp, self.myScrollView.height);
    }else{
        unitY=self.myScrollView.height;
        self.myScrollView.contentSize=CGSizeMake(self.myScrollView.width, self.myScrollView.height*totalPageTemp);
    }
    for (int i=0; i<totalPageTemp; i++) {
        [[NSBundle mainBundle] loadNibNamed:self.pageXibName owner:self options:nil];
        if(self.isCircle)
        {
            self.customView.layer.cornerRadius = 5;
            self.customView.clipsToBounds = YES;
        }
        self.customView.left=unitX*i;
        self.customView.top=unitY*i;
        self.customView.width=self.myScrollView.width;
        self.customView.height=self.height;
        [self.myScrollView addSubview:self.customView];
    }
    
    [self.autoPlayTimer invalidate];
    if(self.isCanAuto)
    {
        self.autoPlayTimer=[NSTimer scheduledTimerWithTimeInterval:AutoPlayTime target:self selector:@selector(autoPlay) userInfo:nil repeats:YES];
    }
    [self refreshScrollView];
}

#pragma mark - 自动播
-(void)autoPlay{
    
    float width=self.myScrollView.width;
    float height=0;
    if (self.floatOrientation == CircleOrientationPortait) {
        width=0;
        height=self.myScrollView.height;
    }
    self.isScrollRunFlag=YES;
//    self.window.userInteractionEnabled=NO;  //让别人不能点击，，否则在动画过程中，点击tabbar，必须闪退。。这个是在视图会消失的情况下，tabbar要保存视图，因为有数组存着，所以不会闪退。。
    [UIView animateWithDuration:.6 animations:^{
        [self.myScrollView setContentOffset:CGPointMake(width*2, height*2)];
    } completion:^(BOOL finished) {
        self.curPageIndex=[self validPageValue:self.curPageIndex+1];
        [self refreshScrollView];
        self.myPageControl.currentPage=self.curPageIndex;
        self.isScrollRunFlag=NO;
//        self.window.userInteractionEnabled=YES;
    }];
    
}

#pragma mark - 填充数据
-(void)refreshScrollView{
    NSArray *curArray=[self getCurDisplayObjectsWithIndex:self.curPageIndex];
    
    if ([self.delegate respondsToSelector:@selector(circleScrollView:refreshThePageWithIndexArray:)]) {
        [self.delegate circleScrollView:self.myScrollView refreshThePageWithIndexArray:curArray];
    
    }
   
    //每次都显示在中间页，只是中间页的内容是会换的.
    if (self.floatOrientation == CircleOrientationLandscape) {
        self.myScrollView.contentOffsetLeft=self.myScrollView.width;
    }else {
        self.myScrollView.contentOffsetTop=self.myScrollView.height;
    }
    
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.isScrollRunFlag) {
        return;
    }
    if (scrollView.dragging) {
        [self.autoPlayTimer invalidate];
    }
    int offSetX=scrollView.contentOffset.x;
    int offSetY=scrollView.contentOffset.y;
    //NSLog(@"did  x=%d  y=%d", offSetX, offSetY);
    //当滑到第三页的时候，则重刷scrollview
    if (self.floatOrientation == CircleOrientationLandscape) {
        if (offSetX >= scrollView.width*2) {
            self.curPageIndex=[self validPageValue:self.curPageIndex+1];
            [self refreshScrollView];
        }
        if (offSetX <= 0) {
            self.curPageIndex=[self validPageValue:self.curPageIndex-1];
            [self refreshScrollView];
        }
    }else {
        if (offSetY >= scrollView.height*2) {
            self.curPageIndex=[self validPageValue:self.curPageIndex+1];
            [self refreshScrollView];
        }
        if (offSetY <= 0) {
            self.curPageIndex=[self validPageValue:self.curPageIndex-1];
            [self refreshScrollView];
        }
    }
    if ([self.delegate respondsToSelector:@selector(circleScrollViewDidScroll:)]) {
        [self.delegate circleScrollViewDidScroll:self.myScrollView];
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.myPageControl.currentPage=self.curPageIndex;
    [self.autoPlayTimer invalidate];
    if(self.isCanAuto)
    {
        self.autoPlayTimer=[NSTimer scheduledTimerWithTimeInterval:AutoPlayTime target:self selector:@selector(autoPlay) userInfo:nil repeats:YES];
    }
}


#pragma mark - 获取需要显示的页的数组
-(NSMutableArray *)getCurDisplayObjectsWithIndex:(int) page{
    int pre= [self validPageValue:page-1];
    int next=[self validPageValue:page+1];
    NSMutableArray *curArray=[[NSMutableArray alloc] init];
    [curArray addObject:[NSNumber numberWithInt:pre]];
    [curArray addObject:[NSNumber numberWithInt:page]];
    [curArray addObject:[NSNumber numberWithInt:next]];
    return curArray;
}
         

#pragma mark - 获取滚动页
- (int)validPageValue:(NSInteger)value {
    if(value == -1) value = self.totalPage-1;
    if(value == self.totalPage) value = 0;
    return value;
}

//－－－－－－－－－－－－－－－－－－－－－－－－－－－公共 end －－－－－－－－－－－－－－－－－－－－－－


@end
